package cn.edu.swu.miniwebsvr.handler;

import cn.edu.swu.miniwebsvr.core.Handler;
import cn.edu.swu.miniwebsvr.core.Parameter;
import cn.edu.swu.miniwebsvr.core.Config;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

// 添加 implements Handler
public class DefaultHandler implements Handler {

    @Override
    public void handle(Parameter request, OutputStream response) {
        // TODO: [2023123456/张三]
        // 1. 获取请求路径（将 / 映射到 index.html）
        String requestPath = request.getUrl();
        if (requestPath.equals("/")) {
            requestPath = "/index.html";
        }

        // 2. 根据 Config.getWebRoot() 构建完整文件路径
        Path filePath = Paths.get(Config.getInstance().getWebRoot(), requestPath.substring(1));

        try {
            if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
                byte[] fileBytes = Files.readAllBytes(filePath);

                // TODO: [2023123456/张三] 确定并设置正确的 Content-Type
                String contentType = Files.probeContentType(filePath);
                if (contentType == null) {
                    // 如果无法探测内容类型，根据文件扩展名判断
                    String fileName = filePath.getFileName().toString();
                    if (fileName.endsWith(".html")) {
                        contentType = "text/html";
                    } else if (fileName.endsWith(".css")) {
                        contentType = "text/css";
                    } else if (fileName.endsWith(".js")) {
                        contentType = "application/javascript";
                    } else if (fileName.endsWith(".png")) {
                        contentType = "image/png";
                    } else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
                        contentType = "image/jpeg";
                    } else {
                        contentType = "application/octet-stream";
                    }
                }

                // 写入 200 OK 响应头
                response.write(("HTTP/1.1 200 OK\r\n").getBytes());
                response.write(("Content-Type: " + contentType + "\r\n").getBytes());
                response.write(("Content-Length: " + fileBytes.length + "\r\n").getBytes());
                response.write(("Connection: close\r\n").getBytes());
                response.write(("\r\n").getBytes());

                // 写入文件内容
                response.write(fileBytes);
            } else {
                // 文件不存在或路径错误，返回 404
                String content = "<h1>404 Not Found</h1><p>The requested resource " + request.getUrl() + " was not found.</p>";
                response.write(("HTTP/1.1 404 Not Found\r\n").getBytes());
                response.write(("Content-Type: text/html; charset=UTF-8\r\n").getBytes());
                response.write(("Content-Length: " + content.getBytes().length + "\r\n").getBytes());
                response.write(("Connection: close\r\n").getBytes());
                response.write(("\r\n").getBytes());
                response.write(content.getBytes());
            }
        } catch (IOException e) {
            // TODO: [2023123456/张三] 文件读取异常，返回 500 Internal Server Error
            try {
                String content = "<h1>500 Internal Server Error</h1><p>Error reading file: " + e.getMessage() + "</p>";
                response.write(("HTTP/1.1 500 Internal Server Error\r\n").getBytes());
                response.write(("Content-Type: text/html; charset=UTF-8\r\n").getBytes());
                response.write(("Content-Length: " + content.getBytes().length + "\r\n").getBytes());
                response.write(("Connection: close\r\n").getBytes());
                response.write(("\r\n").getBytes());
                response.write(content.getBytes());
            } catch (IOException ioException) {
                System.err.println("Error sending 500 response: " + ioException.getMessage());
            }
        } finally {
            try {
                response.flush();
            } catch (IOException e) {
                System.err.println("Error flushing response: " + e.getMessage());
            }
        }
    }
}